<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form :inline="false">
        <el-form-item>
          <el-input
            placeholder="用户名"
            style="width: 230px;"
            v-model="searchParams.username"
          ></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            style="margin:0 20px"
            @click="searchUserName"
            >查询</el-button
          >
          <el-button type="default" @click="clearUserName">清空</el-button>
        </el-form-item>
      </el-form>
      <div style="margin:20px 0">
        <el-button type="primary" @click="addUserItem">添加</el-button>
        <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="deleteAllChecked"
          >批量删除</el-button
        >
      </div>

      <!-- card body -->
      <el-table
        border
        stripe
        :data="userItem"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column label="用户名" prop="username"> </el-table-column>
        <el-table-column label="用户昵称" prop="nickName"> </el-table-column>
        <el-table-column label="角色列表" prop="roleName"> </el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate"> </el-table-column>
        <el-table-column label="更新时间" prop="gmtModified"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-user-solid"
              @click="userCosBtn"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="showUserItem(row)"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="deleteUser(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[3, 5, 7, 9]"
        :page-size="limit"
        layout=" sizes, prev, pager, next, jumper,total"
        :total="total"
        background
      >
        :pager-count="7">
      </el-pagination>
    </el-card>

    <!-- 修改的弹窗 -->
    <el-dialog
      :title="userInfo.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <el-form label-width="80px" :inline="false" size="normal">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="userInfo.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" v-if="!userInfo.id ? true : ''">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updataOraddUserItem">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色设置弹窗 -->
    <el-dialog
      title="角色设置"
      :visible.sync="roleState.roleDialogVisible"
      width="60%"
    >
      <el-form label-width="80px" :inline="false" :data="roleState.allRoles">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <template>
            <el-checkbox
              :indeterminate="roleState.isIndeterminate"
              v-model="roleState.checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group
              v-model="roleState.userRoleIds"
              @change="handleCheckedChange"
            >
              <el-checkbox
                v-for="role in roleState.allRoles"
                :label="role.id"
                :key="role.id"
                >{{ role.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleState.roleDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="assignRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqUserList,
  reqUpdataUser,
  reqDeleteUser,
  reqAddUserItem,
  reqDeleteAllChecked,
  reqUserCosList,
  reqCosFenpeiList
} from "@/api/userInfo";
export default {
  name: "User",
  data() {
    return {
      page: 1, //当前页
      limit: 5, //条数
      total: 100, //总数
      userItem: [], //角色分类
      dialogVisible: false, //弹窗状态
      checked: false, //是否选中，
      // 查询参数
      searchParams: {
        username: "",
        searchname: "" //查询框的内容
      },
      userInfo: {
        id: null,
        username: "", //定义用户名
        nickName: "", //用户昵称
        password: "" //用户密码
      },
      selectedIds: [], //选中批量删除的状态
      roleState: {
        checkAll: false, //全选的状态
        roleDialogVisible: false, //角色的弹窗
        isIndeterminate: false, //半选
        allRoles: [], //角色的权限列表
        userRoleIds: [] //id
      }
    };
  },
  methods: {
    // 页码的回调
    handleSizeChange(val) {
      this.limit = val;
      // console.log(`每页 ${val} 条`);
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.page = val;
      // console.log(`当前页: ${val}`);
      this.getUserList();
    },
    // 请求分页列表数据
    async getUserList() {
      const re = await reqUserList(this.page, this.limit, {
        username: this.searchParams.searchname
      });
      // console.log(re);
      this.userItem = re.data.items;
      this.total = re.data.total;
      this.userInfo.id = this.userItem.map(item => item.id);
      console.log(this.userInfo.id, "ididiidi");
    },

    // 点击修改按钮的事件 数据回填
    showUserItem(row) {
      // 打开弹窗
      this.dialogVisible = true;
      this.userInfo = { ...row };
    },

    // 修改或添加一个用户
    async updataOraddUserItem() {
      if (this.userInfo.id) {
        await reqUpdataUser(this.userInfo);
        this.$message({
          message: "恭喜你，修改成功",
          type: "success"
        });
      } else {
        // 不然就是新增
        await reqAddUserItem(this.userInfo);
        this.$message({
          message: "恭喜你，新增成功",
          type: "success"
        });
        // 清空表单
        this.userInfo = {
          id: null,
          username: "", //定义用户名
          nickName: "", //用户昵称
          password: "" //用户密码
        };
      }
      // 重新发送请求
      this.getUserList();
      // 关闭弹窗
      this.dialogVisible = false;
    },

    // 删除一个用户信息
    async deleteUser(row) {
      await reqDeleteUser(row.id);
      this.$message({
        message: "恭喜你，删除成功",
        showClose: true,
        type: "success"
      });
      // 重新发送请求
      this.getUserList();
    },

    //点击新增的按钮
    addUserItem() {
      // 清空表单
      this.userInfo = {
        username: "",
        nickName: "",
        password: ""
      };
      // 打开弹窗
      this.dialogVisible = true;
    },

    // 是否被选中
    handleSelectionChange(select) {
      this.selectedIds = select.map(item => item.id);
    },

    // 批量删除
    async deleteAllChecked() {
      await reqDeleteAllChecked(this.selectedIds);
      this.$message({
        message: "恭喜你，多个数据删除成功",
        type: "success"
      });
      // 重新发送请求
      this.getUserList();
    },

    // 查找用户名
    searchUserName() {
      this.searchParams.searchname = this.searchParams.username;
      // 重新发送请求
      this.getUserList();
    },
    // 清除搜索框
    clearUserName() {
      this.searchParams.username = "";
      this.getUserList();
    },

    // 角色身份是否全选的函数
    handleCheckAllChange(val) {
      // 如果是全选 长度就相等 要不然就是空数组
      this.roleState.userRoleIds = val
        ? this.roleState.allRoles.map(item => item.id)
        : [];
      // 不是全选的时候
      this.roleState.isIndeterminate = false;
    },
    // 监听的是是否有被选中
    handleCheckedChange() {
      const { userRoleIds, allRoles } = this.roleState;
      this.roleState.checkAll === allRoles.length && allRoles.length > 0;
      this.roleState.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length;
    },

    // 点击角色管理分配的按钮
    userCosBtn() {
      this.roleState.roleDialogVisible = true;
    },
    // 角色的权限请求列表
    async getUserCosList() {
      const result = await reqUserCosList(this.userInfo.id);
      console.log(result, "1222");
      this.roleState.allRoles = result.data.allRolesList;
      // const { allRolesList, assignRoles } = result;
      // this.roleState.userRoleIds = assignRoles?.map(item => item.id);
      // this.roleState.checkAll = allRolesList.length === assignRoles.length;
      // this.roleState.isIndeterminate =
      //   assignRoles.length > 0 && assignRoles.length < allRolesList.length;
    },
    // 分配角色
    async assignRole() {
      const userId = this.userInfo.id;
      const roleIds = this.roleState.userRoleIds.join(",");
      await reqCosFenpeiList(userId, roleIds);
      this.$message({
        message: "恭喜你，分配角色成功",
        type: "success"
      });
      roleState.roleDialogVisible = false;
    }
  },
  mounted() {
    this.getUserList();
    this.getUserCosList();
  }
};
</script>

<style></style>
